package com.bwf.lgqingdan.mvp.presenter.impl;

import com.bwf.lgqingdan.entity.ResponseAllTags;
import com.bwf.lgqingdan.mvp.model.AllTagsModel;
import com.bwf.lgqingdan.mvp.model.impl.AllTagsModelImpl;
import com.bwf.lgqingdan.mvp.presenter.AllTagsPresenter;
import com.bwf.lgqingdan.mvp.view.AllTagsView;
import com.bwf.lgqingdan.utils.Apis;
import com.bwf.lgqingdan.utils.UrlHandler;

/**
 * Created by Administrator on 2016/11/19.
 */

public class AllTagsPresenterImpl implements AllTagsPresenter, AllTagsModel.Callback {
    private AllTagsModel model;
    private AllTagsView view;
    public static final int TAG_NEWEST = 1;
    public static final int TAG_HOTTEST = 2;
    private int tag = TAG_NEWEST;
    private int nextPage = 1;
    public AllTagsPresenterImpl(AllTagsView view) {
        this.view = view;
        this.model = new AllTagsModelImpl();
    }

    @Override
    public void loadInitTags() {
        nextPage = 1;
        loadNextPageTagsSortByHottest();
    }

    @Override
    public void loadNextPageTagsSortByHottest() {
        if(tag != TAG_HOTTEST){
            nextPage = 1;
            tag = TAG_HOTTEST;
        }
        String url = UrlHandler.handlUrl(Apis.API_TAG_ALL_TAGS_SORT_BY_HOTTEST,nextPage);
        model.loadDatas(url,this);
    }

    @Override
    public void loadNextPageTagsSortByNewest() {
        if(tag != TAG_NEWEST){
            nextPage = 1;
            tag = TAG_NEWEST;
        }
        String url = UrlHandler.handlUrl(Apis.API_TAG_ALL_TAGS_SORT_BY_NEWEST,nextPage);
        model.loadDatas(url,this);
    }

    @Override
    public void loadNextPageTags() {
        switch (tag){
            case TAG_NEWEST:
                loadNextPageTagsSortByNewest();
                break;
            case TAG_HOTTEST:
                loadNextPageTagsSortByHottest();
                break;
        }
    }

    @Override
    public void refreshData() {
        nextPage = 1;
        loadNextPageTags();
    }

    @Override
    public void loadSuccess(ResponseAllTags responseAllTags) {
        if(responseAllTags.getData().getMeta().getPagination().getCurrent_page()
                == responseAllTags.getData().getMeta().getPagination().getTotal_pages()){
            view.showNoMoreTags();
        }
        if(nextPage == 1){
            view.finishRefresh();
            view.showFirstPageTags(responseAllTags.getData().getTags());
        }else{
            view.finishRefreshLoadMore();
            view.showNextTags(nextPage,responseAllTags.getData().getTags());
        }
        nextPage++;
    }

    @Override
    public void loadFailed(String failedMsg) {
        view.showLoadTagsFailed(failedMsg);
        if(nextPage == 1){
            view.finishRefresh();
        }else{
            view.finishRefreshLoadMore();
        }
    }
}
